package services

import (
	"app/dao"
	"app/unit"
	"errors"
)

type userService struct{}

var UserService = newUserService()

func newUserService() *userService {
	return &userService{}
}

func (u *userService) Fetch() (us []dao.User) {
	d := &dao.User{}
	us = d.Fetch()
	return
}

func (u *userService) FindById(id int) (us dao.User) {
	d := &dao.User{}
	us = d.FindById(id)
	return
}

func (u *userService) FindByRoleis(roleid int) (us []dao.User) {
	d := &dao.User{}
	us = d.FindByRoleid(roleid)
	return
}

func (u *userService) FindByAccount(account string) (us dao.User) {
	d := &dao.User{}
	us = d.FindByAccount(account)
	return
}

func (u *userService) Save(um *dao.User, members []int) (err error) {
	if um.Account == "" || um.Password == "" {
		return errors.New("账号密码不可为空")
	}
	exist := u.FindByAccount(um.Account)
	if exist.Id > 0 {
		err = um.Save()
	} else {
		um.Password = unit.MD5(um.Password)
		err = um.Insert()
	}
	if err == nil && um.Roleid == 2 && len(members) > 0 {
		mre := &dao.Managerelation{Mid: int(um.Id)}
		memRaletion := make([]dao.Managerelation, len(members))
		for i := 0; i < len(members); i++ {
			memRaletion = append(memRaletion, dao.Managerelation{Mid: int(um.Id), Cid: members[i]})
		}
		memRaletion = append(memRaletion, dao.Managerelation{Mid: int(um.Id), Cid: int(um.Id)})
		err = mre.Insert(memRaletion)
	}
	return
}

func (u *userService) ChangePassword(id int, password string) (err error) {
	user := u.FindById(id)
	if user.Account == "" {
		err = errors.New("账户不存在")
		return
	}
	user.Password = unit.MD5(password)
	err = user.ChangePassword()
	return
}

func (u *userService) Delete(id int) {
	d := &dao.User{}
	d.Delete(id)
}

func (u *userService) FetchMembers(id int) []int {
	mr := &dao.Managerelation{}
	members := mr.FindCidByMid(id)
	membersid := make([]int, len(members))
	for i := 0; i < len(members); i++ {
		membersid = append(membersid, members[i].Cid)
	}
	return membersid
}
